/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.cheln.explorer.ds.database.copersynch;

import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Message;
import android.provider.MediaStore;

import com.direction.hold.ui.CommonActivity;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

import cn.cheln.explorer.beans.FileInfo;
import cn.cheln.explorer.config.Constants;
import cn.cheln.explorer.ds.MediaArgs;
import cn.cheln.explorer.ds.database.MimeSrc;
import cn.cheln.explorer.ds.util.ContentValuesUtil;
import cn.cheln.support.log.Logs;
import cn.cheln.support.images.FileTypeInfo;

/**
 * 
 * @author Administrator
 */
public class DatasrcRename {

	static Thread renamethread = null;

	public static void locate(final FileInfo target,
			final CommonActivity commonActivity) {

		// final int selection =
		// commonActivity.adapter.getPathOnlyItemPos(target);
		// Logs.i("", "===><===>" + target.getPath() + " " + commonActivity +
		// " " + selection);
		// if (selection == -1) {
		// return;
		// }
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(50);
				} catch (InterruptedException ex) {
					Logger.getLogger(DatasrcRename.class.getName()).log(
							Level.SEVERE, null, ex);
				}
				Message mess = commonActivity.handler
						.obtainMessage(Constants.OperationContants.RENAMING);
				mess.obj = target;
				// mess.arg1 = selection;
				// Logs.i("", "===><===>" + mess.arg1);
				commonActivity.handler.sendMessage(mess);

			}
		}).start();

	}

	public static void invokeUpdate(final FileInfo target, final FileInfo src,
			final CommonActivity commonActivity, final boolean dirRename) {
		if (target.getIsDir()) {
			renameBatchUpdate(target, src, commonActivity);
		} else {
			renameSingle(target, src, commonActivity, false);
		}
	}

	public static void renameRecursive(final FileInfo target, final FileInfo src,
                                       final CommonActivity commonActivity, final boolean subdir) {
		if (target.getIsDir()) {
			final File[] fs = target.getFile().listFiles();
			if (fs == null) {
				if (!subdir) {
					locate(target, commonActivity);
				}
				return;
			}
			for (File file : fs) {
				renameRecursive(new FileInfo(file, commonActivity), new FileInfo(
                        src.getPath() + "/" + file.getName()), commonActivity,
                        file.isDirectory());
			}
			renameSingle(target, src, commonActivity, true);
		} else {
			renameSingle(target, src, commonActivity, false);
		}
	}

	public static void renameBatchUpdate(final FileInfo target,
			final FileInfo src, final CommonActivity commonActivity) {
		if (target.getIsDir()) {
			final File[] fs = target.getFile().listFiles();
			if (fs == null) {
				locate(target, commonActivity);
				return;
			}
			if (commonActivity.renameWaitDialog.isShowing()) {
				for (File file : fs) {
					renameRecursive(new FileInfo(file, commonActivity),
                            new FileInfo(src.getPath() + "/" + file.getName()),
                            commonActivity, true);
				}
				renameSingle(target, src, commonActivity, true);
			} else {
				commonActivity.renameWaitDialog.show();
				new Thread() {

					@Override
					public void run() {
						super.run();
						for (File file : fs) {
						renameRecursive(
                                new FileInfo(file, commonActivity),
                                new FileInfo(src.getPath() + "/"
                                        + file.getName()), commonActivity,
                                true);
						}
						renameSingle(target, src, commonActivity, true);
						// locate(target, commonActivity);
						Message msg = new Message();
						msg.obj = target;
						msg.what = Constants.OperationContants.RENAMED;
						commonActivity.handler.sendMessage(msg);
					}
				}.start();
			}
		}
	}

	public static void renameSingle(FileInfo target, FileInfo src,
                                    CommonActivity commonActivity, boolean dirRename) {
		FileTypeInfo targetInfo = FileTypeInfo.getTypeInfo(target);
		if (dirRename) {
			Uri typeNew = null;
//			if (Config.is4_0Lower) {
//				typeNew = targetInfo.uri;
//			} else {
				typeNew = MediaArgs.dirUri;
//			}
//			if (targetInfo.uri != null) {
				ContentValues cv = ContentValuesUtil.constructContentValues(
						target, targetInfo);
				commonActivity.getContentResolver().update(typeNew, cv,
						MediaStore.Audio.Media.DATA + " like ?",
						new String[] { src.getPath() });
//			}
			return;
		}
		target.buildName();
		src.buildName();
		FileTypeInfo srcInfo = FileTypeInfo.getTypeInfo(src);
//		Logs.i("",
//				"===><===> target.path : " + target.getPath() + " "
//						+ targetInfo.ext + " " + srcInfo.ext + " src.path : "
//						+ src.getPath() + " ");

		if (srcInfo.ext.equalsIgnoreCase(targetInfo.ext)) {
			boolean isOnlyPathActivity = false;
			Uri typeNew = null;
//			if (Config.is4_0Lower) {
				typeNew = targetInfo.uri;
//			} else {
//				typeNew = MediaArgs.otherUri;
//			}
			if (targetInfo.uri != null) {
				ContentValues cv = ContentValuesUtil.constructContentValues(
						target, targetInfo);
				commonActivity.getContentResolver().update(typeNew, cv,
						MediaStore.Audio.Media.DATA + " like ?",
						new String[] { src.getPath() });
			} else {
				isOnlyPathActivity = true;
			}

//				if (isOnlyPathActivity) {
//					commonActivity.sort();
//				} else {
//					ActivityPool.getInstance().sortrefresh();
//				}
            Message msg = new Message();
//            msg.obj = target;
            msg.what = Constants.OperationContants.RENAMING;
            commonActivity.handler.sendMessage(msg);
//				locate(target, commonActivity);

		} else {
			// out?
			if (MimeSrc.categoryRepository.containsKey(srcInfo.category)) {
				Logs.i("", "mimePrefix -------------> remove " + srcInfo.mime
						+ " " + srcInfo.category);
				Uri targetUri = null;
//				if (Config.is4_0Lower) {
					targetUri = targetInfo.uri;
//				} else {
//					targetUri = MediaArgs.otherUri;
//				}
                DatasrcDelete.recursiveUpdateDel(src,commonActivity);
//				delete(commonActivity,srcInfo.uri , src.getPath());
//				if (!dirRename) {
//					commonActivity.refresh();
//				}
			}
			// in?
			if (MimeSrc.categoryRepository.containsKey(targetInfo.category)) {
				Logs.i("", "mimePrefix -------------> add " + targetInfo.mime
						+ " " + targetInfo.uri + " " + targetInfo.category);
				ContentValues contentvalues = ContentValuesUtil
						.constructContentValues(target, targetInfo);
				commonActivity.getContentResolver().insert(targetInfo.uri, contentvalues);
			}
//			if (!dirRename
			// && (commonActivity instanceof PathActivity)
//			) {
//				commonActivity.sort();
//				locate(target, commonActivity);
//			}
		}
	}

	public static void delete(Context context, Uri uri, String data) {
		context.getContentResolver().delete(uri, MediaArgs.PATH + " like ?",
				new String[] { data });
	}

}
